package org.fitweb.drivers;

import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import java.util.List;

import static org.fitweb.drivers.BrowserController.DriverType.*;

public class BrowserController {

    private AdaptedWebDriver driver;

    public enum DriverType {

        firefox {AdaptedWebDriver instantiate() {
            return new AdaptedFirefoxDriver();
        }},
        ie {AdaptedWebDriver instantiate() {
            return new AdaptedInternetExplorerDriver();
        }},
        html {AdaptedWebDriver instantiate() {
            return new AdaptedHtmlUnitDriver();
        }},
        chrome {AdaptedWebDriver instantiate() {
            return new AdaptedChromeDriver();
        }};

        static DriverType given(String typeName) {
            return valueOf(typeName.toLowerCase());
        }

        abstract AdaptedWebDriver instantiate();
    }

    public BrowserController(String typeName) {
        if (StringUtils.isBlank(typeName)) typeName = "html";
        this.driver = given(typeName).instantiate();
    }

    public boolean isHtmlUnit() {
        return driver instanceof HtmlUnitDriver;
    }

    public void setProxy(String proxyServer, int port, String username, String password) {
        driver.setProxy(proxyServer, port);
        driver.setCredentials(username, password);
    }

    public String pageContents() {
        return driver.getPageSource();
    }

    public WebDriver.Navigation navigate() {
        return driver.navigate();
    }

    public int getStatusCode() {
        return driver.getStatusCode();
    }

    public String currentUrl() {
        return driver.getCurrentUrl();
    }

    public WebElement findElement(By by) {
        return driver.findElement(by);
    }

    public List<WebElement> findElements(By by) {
        return driver.findElements(by);
    }

    public String innerHtml(WebElement element) {
        return (String) executeJavascript("return arguments[0].innerHTML", element);
    }

    public Object executeJavascript(String script, Object... elements) {
        return driver.executeScript(script, elements);
    }

    public void setRequestHeader(String name, String value) {
        driver.setRequestHeader(name, value);
    }
}